package com.lmn.dao;

import com.lmn.dao.mapper.TestMapper;
import com.lmn.dao.model.Test;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @describe:
 */
@Repository
public class TestDAO {
    @Autowired
    private TestMapper testMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    /**
     * https://mybatis.org/mybatis-dynamic-sql/docs/insert.html
     * 批量插入  量很大时候建议使用，否则建议使用foreach 方式， 不建议使用代码for循环单条插入
     */
    @Transactional
    public void batchInsert() {
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
        TestMapper testMapper = session.getMapper(TestMapper.class);
        testMapper.insert(generateModel(1L));
        testMapper.insert(generateModel(2L));
        session.flushStatements();
        session.commit();
    }

    private Test generateModel(Long id) {
        Test test = new Test();
        test.setId(id);
        test.setName(id + "");
        test.setCreateTime(System.currentTimeMillis());
        test.setUpdateTime(System.currentTimeMillis());
        return test;
    }


    public void batchQuery(TestResultHandler testResultHandler) {
        sqlSessionTemplate.select("batchSelect", testResultHandler);
        testResultHandler.end();
    }

    public void search() {
        List<Test> testList = testMapper.select();
        System.out.println(Arrays.stream(testList.toArray()).toArray());
    }
}
